
var foxySiteDB = {
	//------------------------------------
	//to retrieve data from remote server only after 6 hours of previous update
	FXF_SITE_DB_FILE : 'ezqwdb.sqlite',

	
	
	
	// ================Related Site Part===================
	siteCreateDBQuery : 'CREATE TABLE IF NOT EXISTS site_tbl (sid INTEGER PRIMARY KEY , url TEXT, name TEXT, searchPath TEXT, rssPath TEXT,ranking INTEGER, path TEXT, areaPath TEXT,lastUpdatedDate INTEGER,userRanking INTEGER );',
	
	site2CatCreateDBQuery : 'CREATE TABLE IF NOT EXISTS site2cat_tbl (sid INTEGER PRIMARY KEY , sitesid INTEGER,catsid INTEGER);',

	insertSiteQuery   : 'INSERT INTO site_tbl(sid,url,name,searchPath,rssPath,ranking,path,areaPath,lastUpdatedDate,userRanking) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10);',
	
	updateSiteQuery   : 'UPDATE site_tbl SET url=$1, name=$2, searchPath=$3, rssPath=$4, ranking=$5, path=$6, areaPath=$7, lastUpdatedDate=$8, userRanking=$9 WHERE sid=?10',

	updateSiteContentQuery   : 'UPDATE site_tbl SET url=$1, name=$2, searchPath=$3, rssPath=$4, ranking=$5, userRanking=$6 WHERE sid=?7',

	updateSiteFavoriteFlagQuery:'UPDATE site_tbl SET userRanking=$1 WHERE sid=?2',

	findSiteQueryBySid: 'SELECT * FROM site_tbl WHERE sid = ?1',

	findSiteQueryByurl: 'SELECT * FROM site_tbl WHERE url = ?1',
	
	selectSitesQueryByCatSid  : 'SELECT s.* FROM site_tbl s, site2cat_tbl fl WHERE s.sid = fl.sitesid AND fl.catsid= :catsid ORDER BY s.ranking DESC LIMIT 0,:num',

	selectSitesQueryByCatSid2  : 'SELECT s.* FROM site_tbl s, site2cat_tbl fl, site2cat_tbl fl2 WHERE s.sid = fl.sitesid AND fl.catsid in(:catsids) AND fl2.catsid in(catsids2) AND fl.sitesid = fl2.sitesid  ORDER BY s.ranking DESC LIMIT 0,:num',
	
	insertSite2CatQuery   : 'INSERT INTO site2cat_tbl(sid,sitesid,catsid) VALUES(?1,?2,?3);',
	
	updateSite2CatQuery   : 'UPDATE site2cat_tbl SET sitesid=$1, catsid=$2 WHERE sid=?3',

	findSite2CatQueryBySid: 'SELECT * FROM site2cat_tbl WHERE sid = ?1',

	clearUserFavoriteSiteFlag: 'UPDATE site_tbl SET userRanking=0',
	selectUserFavoriteSites: 'SELECT * FROM site_tbl WHERE userRanking>0 ORDER BY userRanking DESC LIMIT 0,:num',


	// creating a DB:
	_initSiteDB : function() {
		$sqlite.cmd(this.FXF_SITE_DB_FILE, this.siteCreateDBQuery);
		$sqlite.cmd(this.FXF_SITE_DB_FILE, this.site2CatCreateDBQuery);
	},

	// parameterized add record, add parameters as much as you want:
	_addSite : function(site) {
		var s = this._findSiteBySid(site.sid);
		if (s == null) {
			if(_DEBUG) consoleService.logStringMessage("_addSite path="+site.path);	
			$sqlite.cmd(this.FXF_SITE_DB_FILE, this.insertSiteQuery, 
					site.sid, site.url, site.name, site.searchPath, site.rssPath,site.ranking, site.path, site.areaPath, site.lastUpdatedDate,site.userRanking);
		}
	},

	_updateSite : function(site) {
		var s = this._findSiteBySid(site.sid);
		if (s != null) {
			$sqlite.cmd(this.FXF_SITE_DB_FILE, this.updateSiteQuery, 
					site.url, site.name, site.searchPath, site.rssPath, site.ranking,
					site.path, site.areaPath, site.lastUpdatedDate,site.userRanking, site.sid);
		} 
	},

	_updateSiteContent : function(site) {
		var s = this._findSiteBySid(site.sid);
		if (s != null) {
			$sqlite.cmd(this.FXF_SITE_DB_FILE, this.updateSiteContentQuery, 
					site.url, site.name, site.searchPath, site.rssPath, site.ranking,site.userRanking, site.sid);
		} 
	},

	

	_findSiteByUrl : function(url) {
		var sValues = $sqlite.select(this.FXF_SITE_DB_FILE,this.findSiteQueryByurl, url);
		var site;
		if (sValues && sValues.length > 0) {
			var s = sValues[0];
			site = new Site(s.sid, s.url, unescape(s.name), s.searchPath, s.rssPath, s.ranking, s.path, s.areaPath, s.lastUpdatedDate,s.userRanking);
		}
		return site;
	},

	_findSiteBySid : function(sid) {
		var sValues = $sqlite.select(this.FXF_SITE_DB_FILE,this.findSiteQueryBySid, sid);
		var site = null;
		if (sValues && sValues.length > 0) {
			var s = sValues[0];
			site = new Site(s.sid, s.url, unescape(s.name), s.searchPath, s.rssPath ,s.ranking, s.path, s.areaPath, s.lastUpdatedDate,s.userRanking);
		}
		return site;
	},

	_findSite2CatBySid : function(sid) {
		var sValues = $sqlite.select(this.FXF_SITE_DB_FILE,this.findSite2CatQueryBySid, sid);
		var link = null;
		if (sValues && sValues.length > 0) {
			var s = sValues[0];
			link = new Site2Cat(s.sid, s.sitesid,s.catsid);
		}
		return link;
	},

	_addSite2Cat : function(link) {
		var s = this._findSite2CatBySid(link.sid);
		if (s == null) {
			$sqlite.cmd(this.FXF_SITE_DB_FILE, this.insertSite2CatQuery, 
					link.sid,link.sitesid, link.catsid);
		}
	},

	_updateSite2Cat : function(link) {
		var s = this._findSite2CatBySid(link.sid);
		if (s != null) {
			$sqlite.cmd(this.FXF_SITE_DB_FILE,this.updateSite2CatQuery, 
					link.sitesid, link.catsid,link.sid);
		} 
	},

	_clearUserFavoriteSiteFlag : function() {
		$sqlite.cmd(this.FXF_SITE_DB_FILE,this.clearUserFavoriteSiteFlag);
	},

	_selectUserFavoriteSites : function(num) {
		var sValues = $sqlite.select(this.FXF_SITE_DB_FILE,this.selectUserFavoriteSites,num);
		var result = null;
		if (sValues && sValues.length > 0) {
			result = new Array();
			for (var i = 0; i < sValues.length; i++) {
				var s = sValues[i];
				var site = new Site(s.sid,s.url, s.name, s.searchPath, s.rssPath ,s.ranking, s.path, s.areaPath, s.lastUpdatedDate,s.userRanking);
				result.push(site);
			}
		}
		return result;

	},
		

	// select with bound parameters, add parameters as much as you want:
	_selectSitesByCatSid : function(catsid,num) {

		var sValues = $sqlite.select(this.FXF_SITE_DB_FILE,this.selectSitesQueryByCatSid, catsid,num);
		var result = null;
		if (sValues && sValues.length > 0) {
			result = new Array();
			for (var i = 0; i < sValues.length; i++) {
				var s = sValues[i];
				var site = new Site(s.sid,s.url, s.name, s.searchPath, s.rssPath ,s.ranking, s.path, s.areaPath, s.lastUpdatedDate,s.userRanking);
				result.push(site);
			}
		}
		return result;
	},

	
	_syncUserFavoriteSitesFromServer : function() {
		var isOutDate = true;
		if(isOutDate  == true) {
			var urlpara="";
			if(fxf_pref_enablesignature) urlpara = "?" + fxf_pref_signature;

			$.ajax({
				type : "GET",
				dataType : "json",
				url : CONFIG_SERVER_GET_USER_FAVORITE_LINKS_URL,//"http://localhost:8080/jubao/ajaxgetfavoritewebsite.php",
				data : urlpara, // 要发送的数据
				success : function(jd) {
					if(_DEBUG) consoleService.logStringMessage("ajax _syncUserFavoriteSitesFromServer get jd="+JSON.stringify(jd));
					var now = new Date();
					//1.-----process site data--------
					if (jd && jd["site"]) {
						foxySiteDB._clearUserFavoriteSiteFlag();
						$.each(jd["site"], function(i, s) {
							if(s[0]){
								//$site['sid'],$site['url'],$site['name'],$site["searchpath"],$site["rsspath"],$site['favoriteranking'],$site["ranking"]
								site = new Site(s[0], s[1], s[2], s[3], s[4],s[6],FXF_NULL_STRING, FXF_NULL_STRING, 1,s[5]);

								var osite = foxySiteDB._findSiteBySid(s[0]);
								if(osite == null){
									//function Site(sid, url, name, searchPath,rssPath, ranking, path, areaPath, lastUpdatedDate,userRanking)
									foxySiteDB._addSite(site);
								}else{
									foxySiteDB._updateSiteContent(site);
								}
							}
						});
					}
				},
				complete : function() { 
					if(_DEBUG) consoleService.logStringMessage("ajax complete update user favorite sites");
				}
			});
		}
	},

	_syncSitesFromServer : function(url,updateInterval) {

		var isOutDate = true;
		var site = this._findSiteByUrl(url);
		if(site){
			var now = new Date();
			var lastUpdatedDate = new Date(site.lastUpdatedDate);
			var elapse =  now - (lastUpdatedDate?lastUpdatedDate:0) ;
			if(_DEBUG) consoleService.logStringMessage("_syncSitesFromServer["+CONFIG_SERVER_GET_LINKS_URL+"] url="+url+" now="+now+" site.lastUpdatedDate="+site.lastUpdatedDate+" elapse="+elapse +" updateInterval="+updateInterval);	
			if(elapse < updateInterval) isOutDate = false;
		}

		if(_DEBUG) consoleService.logStringMessage("_syncSitesFromServer isOutDate="+isOutDate+" url="+url);	

		if(isOutDate  == true) {
			var urlpara="";
			if(fxf_pref_enablesignature) urlpara = "&" + fxf_pref_signature;

			$.ajax({
				type : "GET",
				dataType : "json",
				url : CONFIG_SERVER_GET_LINKS_URL,//"http://localhost:8080/jubao/ajaxgetrelatewebsite.jsp",
				data : "url=" + url + urlpara, // 要发送的数据
				success : function(jd) {
					var now = new Date();
					//1.-----process site data--------
					if (jd["site"]) {
						$.each(jd["site"], function(i, s) {
							if(s[0]){
								if(_DEBUG) consoleService.logStringMessage("_syncSitesFromServer ajax get site=["+s+"] path="+jd["path"]+" areaPath="+jd["areaPath"]+" url="+url);
								var site = foxySiteDB._findSiteBySid(s[0]);
								if(site == null){
									//array($site["sid"],$site["url"],$site["name"],$site["searchpath"],$site["rsspath"],$site["ranking"]);
									if(s[1] == url) {
										//-----the site's primary path
										site = new Site(s[0], s[1], s[2], s[3], s[4], s[5], jd["path"], jd["areaPath"], now,-1,"");							
									}else{
										site = new Site(s[0], s[1], s[2], s[3], s[4], s[5],FXF_NULL_STRING, FXF_NULL_STRING, 1,-1,"");
									}
									foxySiteDB._addSite(site);
								}else{
									if(s[1] == url) {//only if myself
										//-----the site's primary path
										site = new Site(s[0], s[1], s[2], s[3], s[4], s[5], jd["path"], jd["areaPath"], now,site.userRanking);	
										if(_DEBUG) consoleService.logStringMessage("_syncSitesFromServer update site=["+JSON.stringify(site)+"] for url="+url);
										foxySiteDB._updateSite(site);
									}
								}
							}
						});
					}
					//2.-----process s2c data
					if (jd["s2c"]) {
						$.each(jd["s2c"], function(i, s2c) {
							var link = foxySiteDB._findSite2CatBySid(s2c[0]);
							if(s2c[0]){
								if(link == null){
									//$s2c["sid"],$s2c["sitesid"],$s2c["catsid"]
									link = new Site2Cat(s2c[0], s2c[1], s2c[2]);
									foxySiteDB._addSite2Cat(link);
								}else{
									link = new Site2Cat(s2c[0], s2c[1], s2c[2]);
									foxySiteDB._updateSite2Cat(link);
								}
							}
						});
					}
				},
				complete : function() { 
					if(_DEBUG) consoleService.logStringMessage("_syncSitesFromServer ajax complete update jd for ["+CONFIG_SERVER_GET_LINKS_URL+"?url="+url);
				}
			});
		}
	},

	getRelatedSites : function(url,type) {
		var result = null;
		var num = 0;
		if(type=="byArea") num = fxf_pref_area_site_number;	else  num = fxf_pref_content_site_number;

		if (num > 0){
			if(_DEBUG) consoleService.logStringMessage("*********1 getRelatedSites url="+url+" type="+type);	

			var site = this._findSiteByUrl(url);
			if(site){
				var path = site.path;
				if(type == "byArea") path = site.areaPath;

				if (path && path != FXF_NULL_STRING) {			
					if(_DEBUG) consoleService.logStringMessage("*********2 getRelatedSites url="+url+" type="+type+" path="+path);	
					var catsids = path.split(",");
					for (var i = 0; i < catsids.length; i++){
						if(i == 0) sites = this._selectSitesByCatSid(catsids[i],num);
						else sites = this._selectSitesByCatSid(catsids[i],num);

						if(result){
							if(sites) result = result.concat(sites);
						}else{
							result = sites;
						}
						if(i == 0 && result && (result.length >= num)) break;
					}
				}

				if(result) result = unique(result);
				if (result && result.length > num) result = result.splice(0,num);

				if(_DEBUG) consoleService.logStringMessage("getRelatedSites type="+type+" url="+url+" result="+JSON.stringify(result));	
			}
		}
		return result;
	},

	getCommonSites : function() {
		this._syncUserFavoriteSitesFromServer();
		var result = this._selectUserFavoriteSites(fxf_pref_common_site_number);
		if(_DEBUG) consoleService.logStringMessage("getCommonSites (_selectUserFavoriteSites) result="+JSON.stringify(result));	
		return result;
	}
};


/**
 * Removes duplicates in the array 'sites'
 */
function unique(sites) {
	tmp = new Array(0);
	if(sites && sites.length > 0){
		for(i=0;i<sites.length;i++){
			if(!contains(tmp, sites[i]["sid"])){
				tmp.length+=1;
				tmp[tmp.length-1]=sites[i];
			}
		}
	}
	return tmp;
};

function contains(sites, sid) {
	if(sites && sites.length > 0){
		for(j=0;j<sites.length;j++){
			if(sites[j]["sid"]==sid){
				return true;
			}
		}
	}
	return false;
};

function Site(sid, url, name, searchPath,rssPath, ranking, path, areaPath, lastUpdatedDate,userRanking) {			
	this.sid = 0;
	this.url = FXF_NULL_STRING;
	this.name = FXF_NULL_STRING;
	this.searchPath = FXF_NULL_STRING;
	this.rssPath = FXF_NULL_STRING;
	this.ranking = 0;
	this.path = FXF_NULL_STRING;
	this.areaPath = FXF_NULL_STRING;
	this.lastUpdatedDate = 0;
	this.userRanking = 0;
	
	if(sid) this.sid = sid;
	if(url) this.url = url;
	if(name) this.name = name;
	if(searchPath) this.searchPath = searchPath;
	if(rssPath) this.rssPath = rssPath;
	if(ranking) this.ranking = ranking;
	if(path) this.path = path;
	if(areaPath) this.areaPath = areaPath;
	if(lastUpdatedDate) this.lastUpdatedDate = lastUpdatedDate;
	if(userRanking) this.userRanking = userRanking;
};

function Site2Cat(sid, sitesid,catsid) {			
	this.sid = 0;
	this.sitesid = 0;
	this.catsid = 0;

	if(sid) this.sid = sid;
	if(sitesid) this.sitesid = sitesid;
	if(catsid) this.catsid = catsid;
};

//initialize database
foxySiteDB._initSiteDB();